package com.qf.fmall01.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fmall01.utils.JwtUtils;
import com.qf.fmall01.vo.ResStatus;
import com.qf.fmall01.vo.ResultVO;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行options请求
        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }

        String token = request.getHeader("token"); //  从请求头中取token
        System.out.println("prehandle ================="+token);

        if (token == null) {
            ResultVO vo = new ResultVO(ResStatus.NO, "请先登录", null);
            doResponse(vo,response);
            return false;
        }

        if(JwtUtils.parseToken(token)){
            return true;
        }else{
            ResultVO vo = new ResultVO(ResStatus.NO, "请先登录", null);
            doResponse(vo,response);
            return false;
        }
    }

    private void doResponse(ResultVO vo, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(vo);
        out.print(s);
        out.flush();
        out.close();


    }
}
